package com.ruoyi.common.utils.ip;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 获取地址类
 * 
 * @author ruoyi
 */
public class AddressUtils
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "XX XX";

    private static RedisTemplate redisTemplate = SpringUtils.getBean("redisTemplate");
    private static String ADDRESS_KEY = "AddressUtil:";

    public static String getRealAddressByIP(String ip)
    {
        String address1 = (String) redisTemplate.opsForValue().get(ADDRESS_KEY + ip);
        if (StringUtils.isNotEmpty(address1)) {
            return address1;
        }

        String address = UNKNOWN;
        // 内网不查询
        if (IpUtils.internalIp(ip))
        {
            return "内网IP";
        }
        if (RuoYiConfig.isAddressEnabled())
        {
            try
            {
                String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK);
                if (StringUtils.isEmpty(rspStr))
                {
                    log.error("获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                JSONObject obj = JSON.parseObject(rspStr);
                String pro = obj.getString("pro");
                String city = obj.getString("city");
                //输出区（县）名称
                String region = obj.getString("region");
                if (pro.equals(city)) {
                    address = String.format("%s %s", pro, region);
                }else{
                    address = String.format("%s %s %s", pro, city, region);
                }
                redisTemplate.opsForValue().set(ADDRESS_KEY + ip, address, 60L, TimeUnit.MINUTES);
                return address;
            }
            catch (Exception e)
            {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return UNKNOWN;
    }
}
